/**
 * @file uuap
 * @author: fanlei04
 * @Date: 2018-10-25
 * @Last Modified by: v_xieyejiang
 * @Last Modified time: 2018-12-10 14:48:37
 */
'use strict';

const querystring = require('querystring');
const config = require('../config');
const xml2js = require('xml-js');
const setRes = require('../utils/setRes');
const requestPromise = require('request-promise');

class UUAP {
    static auth(req, res, next) {
        const authorigin = req.headers.authorigin;
        let ticket = req.headers.ticket;
        let views = req.session && req.session.views;
        let service;
        if (views && views.userName) {
            global.console.info('***111***');
            next();
        }
        else if (ticket) {
            global.console.info('***222***');
            !views && (req.session.views = {});
            service = authorigin;
            let postData = querystring.stringify({
                ticket: ticket,
                service: service,
                appKey: config.appKey
            });
            let options = {
                method: 'POST',
                uri: `${config.uuapUrl}/serviceValidate`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(postData)
                },
                body: postData
            };
            global.console.info('***ticket validate***');
            requestPromise(options)
                .then(data => {
                    return validateTicket(data);
                })
                .then(data => {
                    if (data.code === 'success') {
                        const userName = data.userName;
                        req.session.views.userName = userName;
                        setRes(res, 401, {
                            callback: service
                        });
                    }

                });
        }
        else {
            global.console.info('***333***');
            const uuapOrigin = `${config.uuapUrl}/login`;
            const uuapService = `service=${encodeURIComponent(authorigin)}`;
            const uuapAppKey = `appKey=${config.appKey}`;
            const redirecturl = `${uuapOrigin}?${uuapService}&${uuapAppKey}`;
            setRes(res, 401, {
                callback: redirecturl
            });
        }

        // 校验uuap服务器
        // @param {*} response  接口请求uuap服务器校验完的返回键结果
        function validateTicket(response) {
            return new Promise((resolve, reject) => {
                let userName;
                let userInfo;
                let responseJSON = JSON.parse(
                    xml2js.xml2json(response, {compact: true, spaces: 4})
                );
                if (responseJSON['cas:serviceResponse']['cas:authenticationFailure']) {
                    let rep = responseJSON['cas:serviceResponse']['cas:authenticationFailure'];
                    let errorInfo = {
                        code: rep._attributes.code,
                        text: rep._text
                    };
                    resolve(errorInfo);
                }
                else if (
                    responseJSON['cas:serviceResponse']['cas:authenticationSuccess']
                ) {
                    let rep = responseJSON['cas:serviceResponse']['cas:authenticationSuccess'];
                    global.console.info('***login info***');
                    // 解析UUAP用户名
                    userName = rep['cas:user']._text;
                    resolve({
                        code: 'success',
                        userName: userName,
                        userInfo: userInfo
                    });
                }
                else {
                    resolve({
                        code: 'fail'
                    });
                }
            });
        }
    }
    static logout(req, res, next) {
        global.console.info('***logout***');
        delete req.session.views; // 销毁session
        const redirecturl = `${config.uuapUrl}/logout?service=${req.query.callback}`;
        setRes(res, 401, {
            callback: redirecturl
        });
    }
}
module.exports = UUAP;
